'use strict';

var express = require('express');
var timeout = require('connect-timeout');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var AV = require('leanengine');
var apicache = require('apicache')
var users = require('./routes/acfun/users');
var contents = require('./routes/acfun/contents');
var novels = require('./routes/novels/novels');
var ukcharts = require('./routes/ukcharts/ukcharts');
var api = require('./routes/api/api');
var user = require('./routes/user');
var kindle = require('./routes/kindle');
var agnscore = require('./routes/agnscore');

// 加载云函数定义，你可以将云函数拆分到多个文件方便管理，但需要在主文件中加载它们
require('./cloud');

var app = express();

let cache = apicache.middleware
const onlyStatus200 = (req, res) => {
    return !req.path.startsWith('/kindle') && !req.path.startsWith('/agnscore') &&  res.statusCode === 200
}

// 跨域设置
app.all('*', function (req, res, next) {
    if (!req.path.startsWith('/kindle') && req.path !== '/' && !req.path.includes('.')) {
        res.header('Access-Control-Allow-Credentials', true)
        // 这里获取 origin 请求头 而不是用 *
        res.header('Access-Control-Allow-Origin', '*')
        res.header('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type')
        res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
        res.header('Content-Type', 'application/json;charset=utf-8')
    }
    next()
})

app.use(cache('5 minutes', onlyStatus200))

// 设置模板引擎
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

app.use(express.static('public'));

// 设置默认超时时间
app.use(timeout('15s'));

// 加载云引擎中间件
app.use(AV.express());

app.enable('trust proxy');
// 需要重定向到 HTTPS 可去除下一行的注释。
// app.use(AV.Cloud.HttpsRedirect());

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

//Acfun
app.use('/acfun/contents', contents)
app.use('/novels', novels);
app.use('/ukcharts', ukcharts);
app.use('/user', user);
app.use('/acfun/users', users);
app.use('/api', api);
app.use('/kindle', kindle);
app.use('/agnscore', agnscore);
app.use(function(req, res, next) {
    // 如果任何一个路由都没有返回响应，则抛出一个 404 异常给后续的异常处理器
    if (!res.headersSent) {
        var err = new Error('Not Found');
        err.status = 404;
        next(err);
    }
});

// error handlers
app.use(function(err, req, res, next) {
    if (req.timedout && req.headers.upgrade === 'websocket') {
        // 忽略 websocket 的超时
        return;
    }

    var statusCode = err.status || 500;
    if (statusCode === 500) {
        console.error(err.stack || err);
    }
    if (req.timedout) {
        console.error('请求超时: url=%s, timeout=%d, 请确认方法执行耗时很长，或没有正确的 response 回调。', req.originalUrl, err.timeout);
    }
    res.status(statusCode);
    // 默认不输出异常详情
    var error = {};
    if (app.get('env') === 'development') {
        // 如果是开发环境，则将异常堆栈输出到页面，方便开发调试
        error = err;
    }
    res.send({
        message: err.message,
        code: err.status,
        error: error
    });
});

module.exports = app;
